package com.ruoyi.system.Fdongbei.service.impl;

import com.ruoyi.system.Fdongbei.domain.TbSdI;
import com.ruoyi.system.Fdongbei.domain.TbWlccfw;
import com.ruoyi.system.Fdongbei.mapper.TbKdpMapper;
import com.ruoyi.system.Fdongbei.service.ITbKdpService;
import com.ruoyi.system.Fdongbei.service.ITbSdIService;
import com.ruoyi.system.Fdongbei.service.ITbWlccfwService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author fufeng
 * @since 2024-12-19
 */
@Service
public class TbKdpServiceImpl implements ITbKdpService {


    @Resource
    ITbSdIService iTbSdIService;

    @Resource
    ITbWlccfwService iTbWlccfwService;

    @Resource
    TbKdpMapper tbKdpMapper;


    public int insertbkdp(String vbeln, String czbh) {

        TbSdI tbSdI = iTbSdIService.selectSdI(vbeln);
        if (tbSdI == null) {
            return -1;
        }
        TbWlccfw tbWlccfw = iTbWlccfwService.selectWlccfw("内销", tbSdI.getMatnr(), tbSdI.getBezei());
        if (tbWlccfw == null) {
            return -1;
        }
        Double yfsl = Double.valueOf(tbSdI.getLfimg());
        Double dp_c = Double.valueOf(tbWlccfw.getDp());
        Double gbbzMin = Double.valueOf(tbWlccfw.getGbbz());
        Double gbbzMax = Double.valueOf(tbWlccfw.getGbbz1());
        Double dpMin = (yfsl / dp_c) * gbbzMin + yfsl;//最低过磅标准
        //计算袋皮最高
        Double dpMax = (yfsl / dp_c) * gbbzMax + yfsl;//最高过磅标准

        if (tbKdpMapper.countkdpbyczbh(czbh) > 0) {
            return tbKdpMapper.updatekdp(Round(dpMin), Round(dpMax), czbh);
        } else {
            return tbKdpMapper.insertkdp(Round(dpMin), Round(dpMax), czbh);
        }


    }


    public static String Round(double v) {
        try {
            // 四舍五入到整数
            long rounded = Math.round(v);

            // 去掉个位数
            long withoutUnits = (rounded / 10) * 10;

            // 获取十位数
            int tenth = (int) ((withoutUnits / 10) % 10);

            // 如果十位数是奇数，减1变为偶数
            if (tenth % 2 != 0) {
                withoutUnits -= 10;
            }

            // 个位数已经是0，无需额外操作
            return String.valueOf(withoutUnits);
        } catch (Exception e) {
            return String.valueOf(v);
        }
    }

}
